package org.fall.mvc.handler;

import com.atguigu.crowd.util.ResultEntity;
import com.atguigu.crowd.entity.Auth;
import com.atguigu.crowd.entity.Role;
import org.fall.service.api.AdminService;
import org.fall.service.api.AuthService;
import org.fall.service.api.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
public class AssignHandler {

    @Autowired
    private RoleService roleService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private AuthService authService;


    @ResponseBody
    @RequestMapping("assign/do/save/role/auth/relationship.json")
    public ResultEntity<String> saveRoleAuthRelathinship(
            @RequestBody Map<String, List<Integer>> map
    ) {

        authService.saveRoleAuthRelathinship(map);

        return ResultEntity.successWithoutData();
    }

    @RequestMapping("assign/get/checked/auth/id.json")
    @ResponseBody
    public ResultEntity<List<Integer>> getAssigned(@RequestParam("roleId") Integer roleId) {

        List<Integer> authId = authService.getAssignedAuthIdByRoleId(roleId);

        return ResultEntity.successWithData(authId);
    }


    @ResponseBody
    @RequestMapping("assign/get/tree.json")
    public ResultEntity<List<Auth>> getAllAuth() {

        List<Auth> authList = authService.getAll();

        return ResultEntity.successWithData(authList);
    }


    @RequestMapping("assign/to/page.html")
    public String toAssignPage(@RequestParam("adminId") Integer adminId, ModelMap modelMap) {
        //未分配的
        List<Role> UnAssignedRoleList = roleService.getUnAssignedRoleList(adminId);

        //已分配的
        List<Role> AssignedRoleList = roleService.getAssignedRoleList(adminId);

        modelMap.addAttribute("UnAssignedRoleList", UnAssignedRoleList);
        modelMap.addAttribute("AssignedRoleList", AssignedRoleList);

        return "assign-role";
    }


    @RequestMapping("assign/do/assign.html")
    public String saveAdminRoleRelationship(
            @RequestParam("adminId") Integer adminId,
            @RequestParam("pageNum") Integer pageNum,
            @RequestParam("keyword") String keyword,
            //允许没有权限
            @RequestParam(value = "roleIdList", required = false) List<Integer> roleIdList
    ) {

        adminService.saveAdminRoleRelationship(adminId, roleIdList);

        return "redirect:/admin/page/page.html?pageNum=" + pageNum + "&keyword=" + keyword;
    }

}
